package com.example.smartagrisys.config;

import com.example.smartagrisys.interceptor.JwtAuthenticationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Web MVC配置
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private static final Logger log = LoggerFactory.getLogger(WebMvcConfig.class);

    @Autowired
    private JwtAuthenticationInterceptor jwtAuthenticationInterceptor;
    
    @Value("${file.upload.path:/tmp/uploads/}")
    private String uploadPath;

    /**
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtAuthenticationInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/auth/login",
                        "/auth/register",
                        "/error",
                        "/swagger-resources/**",
                        "/swagger-ui/**",
                        "/v3/api-docs/**",
                        "/webjars/**",
                        "/product/upload/image/**",
                        "/product/image/**",
                        "/images/**",
                        "/uploads/**",
                        "/file/**"
                );
    }

    /**
     * 跨域配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
    
    /**
     * 添加静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 上传文件夹映射
        String absolutePath = getAbsoluteUploadPath();
        log.info("注册静态资源路径: /file/** -> {}", absolutePath);
        registry.addResourceHandler("/file/**")
                .addResourceLocations("file:" + absolutePath + "/");
    }
    
    /**
     * 获取上传目录的绝对路径
     */
    private String getAbsoluteUploadPath() {
        String path = uploadPath;
        
        // 如果以./开头，则基于当前用户目录处理
        if (path.startsWith("./")) {
            path = System.getProperty("user.dir") + path.substring(1);
        } 
        // 如果不是绝对路径，则基于用户目录创建绝对路径
        else if (!path.startsWith("/") && !path.matches("^[A-Za-z]:\\\\.*")) {
            path = System.getProperty("user.dir") + File.separator + path;
        }
        
        return path;
    }
} 